package com.yinshu.teleshield.tkbase.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.yinshu.teleshield.tkbase.base.R;
import com.yinshu.teleshield.tkbase.controller.helper.PlusSheetWriteHandler;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;

@Slf4j
public final class ExcelEasyUtils {

    /**
     * @param response              response
     * @param filename              导出的文件名
     * @param clazzVO               导出的数据类型
     * @param list                  导出的数据
     * @param hand                  导出的表头
     * @param plusSheetWriteHandler 自定义的sheet写入处理器
     * @throws IOException
     */
    public static void exportExcel(HttpServletResponse response, String filename, Class<?> clazzVO, List<?> list, List<List<String>> hand, PlusSheetWriteHandler plusSheetWriteHandler) throws IOException {
        try {
            String fileName = URLEncoder.encode(filename, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            ExcelWriterBuilder write = EasyExcel.write(response.getOutputStream(), clazzVO);
            Optional.ofNullable(hand).filter(CollUtil::isNotEmpty).ifPresent(write::head);
            write.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy());
            write.registerWriteHandler(plusSheetWriteHandler);
            write.sheet("模板").doWrite(list);
        } catch (Exception e) {
            log.error("导出失败", e);
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            R error = R.fail("下载文件失败");
            response.getWriter().println(JSONUtil.toJsonStr(error));
        }
    }
}
